import 'package:ai_desktop_eidtor/common/y_alert.dart';
import 'package:ai_desktop_eidtor/models/hive_models.dart';
import 'package:ai_desktop_eidtor/util/y_req.dart';
import 'package:get/get.dart';

import '../../../models/BookChapterRepository.dart';
import 'book_detail_state.dart';

class BookDetailLogic extends GetxController {
  final BookDetailState state = BookDetailState();
  String bookId = '';
  final repository = BookChapterRepository();
  BookModel? bookModel;
  ChapterModel? chapterModel;
  @override
  void onReady() {
    // TODO: implement onReady
    bookId = Get.arguments;
    super.onReady();
    loadData();
  }

  void loadData({bool canLoad = false}) async{
    yGet(load: (repository) async{
      bookModel = await repository.getBookById(bookId);
    },finalBlock: (){
      loadChapter();
      if(canLoad){
        updateBook();
      }
    });

  }
  void loadChapter({bool canLoad = false}) async{
    yGet(load: (repository) async{
      List<ChapterModel> arr = await repository.getChaptersByBook(bookId);
      if(arr.isNotEmpty){
        chapterModel = arr.last;
      }
      update();
    },finalBlock: (){
      if(canLoad){
        updateBook();
      }
    });
  }
  void deleteBook() {
    YAlert.show('是否确定删除该书籍,删除后将再也无法查询到书籍内容?',okBlock: () async{
      await repository.init();
      repository.deleteBook(bookId);
      repository.close();
      Get.back(result: true);
    });

  }

  void updateBook(){
    yPost(load: (res)async{
      BookModel? bm = await res.getBookById(bookId);
      bm?.updatedAt = DateTime.now();
      await res.updateBook(bookId,bm!);
    },finalBlock: (){
      loadData(canLoad: false);
    });
  }
}
